﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Top.Web;
using Top.Core;
using Top.Web.Api;

namespace Top.Business.OAuth
{
    public static class OAuthHelper
    {

        public static string oauthUrl = Configs.AppSettings.Get("OAuth.Domain");

        public static string oauthOnOff = Configs.AppSettings.Get("OAuthOnOff");

        public static string notifyUrl = Configs.AppSettings.Get("notifyUrl");

        public static string SignIn(string loginName, string password)
        {
            // http://oauth.beta.tops001.com/SignIn/SignInAccount
            var request = new HttpRequest(oauthUrl);
            request.Path = "SignIn/SignInAccount?ver=1.0";
            request.QueryString.Add("loginName", loginName);
            request.QueryString.Add("password", Top.Common.TopEncrypt.EncryptMD5_1(password));
            request.Sign();
            var result = request.Kakao<dynamic>().Result;
            if (result.Code != 0)
            {
                ErrorConvert(result.Code.ToString());
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        public static string SignInAccountByOA(string loginName, string password)
        {
            //http://oauth.test.tops001.com/Unsafe/SignInPhoneIgnoreCode
            var request = new HttpRequest(oauthUrl);
            request.Path = "Unsafe/SignInPhoneIgnoreCode?ver=1.0";
            request.QueryString.Add("phone", loginName);
            request.QueryString.Add("password", Top.Common.TopEncrypt.EncryptMD5_1(password));
            request.Sign();
            var result = request.Kakao<dynamic>().Result;
            if (result.Code != 0)
            {
                ErrorConvert(result.Code.ToString());
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        public static string SuperSignIn(string loginName, string password)
        {
            //string Rx = @"^[1-9]\d*$";
            string Rx = @"^[1]([0-9]{1}[0-9]{1}|59|58|88|89)[0-9]{8}$";
            bool isNum = Regex.IsMatch(loginName, Rx);
            if (isNum&&loginName.Length==11)
            {
                return SignInAccountByOA(loginName, password);
            }
            else
            {
                return SignIn(loginName, password);
            }
        }

        public static string SendPhoneCode(string phone)
        {
            // http://oauth.beta.tops001.com/SignIn/SignInAccount
            var request = new HttpRequest(oauthUrl);
            request.Path = "SignIn/SendPhoneCode?ver=1.0";
            request.FormBody.Add("phone", phone);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        public static void ChangePwd(string loginName, string oldPwd, string newPwd, bool isGuid = false)
        {
            if (oauthOnOff.ToLower() == "off")
            {
                return;
            }
            //http://oauth.beta.tops001.com/Authorization/ChangePassword
            if (!isGuid && string.IsNullOrWhiteSpace(oldPwd))
            {
                ForceChangePassword(loginName, newPwd);
                return;
            }
            var request = new HttpRequest(oauthUrl);
            request.Path = "Authorization/ChangePassword?ver=1.0";
            request.QueryString.Add("loginName", loginName);
            request.QueryString.Add("oldpwd", oldPwd);
            request.QueryString.Add("newpwd", Top.Common.TopEncrypt.EncryptMD5_1(newPwd));
            request.Sign();
            var result = request.Kakao<dynamic>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
        }

        public static void ForceChangePassword(string loginName, string newPwd)
        {
            var request = new HttpRequest(oauthUrl);
            request.Path = "Authorization/ForceChangePassword?ver=1.0";
            request.QueryString.Add("loginName", loginName);
            request.QueryString.Add("newpwd", Top.Common.TopEncrypt.EncryptMD5_1(newPwd));
            request.Sign();
            var result = request.Kakao<dynamic>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
        }

        public static OAuthUser Login(string loginName, string password)
        {
            // http://oauth.test.tops001.com/Authorization/Login
            var request = new HttpRequest(oauthUrl);
            request.Path = "Authorization/UnsafeLogin?ver=1.0";
            request.QueryString.Add("loginName", loginName);
            request.QueryString.Add("password", password);
            request.Sign();
            var result = request.Kakao<OAuthLoginData>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            OAuthUser userData = GetUser(result.Data.UserToken);
            return userData;
        }


        public static OAuthUser UnsafeLogin(string loginName, string password)
        {
            // http://oauth.test.tops001.com/Authorization/UnsafeLogin
            var request = new HttpRequest(oauthUrl);
            request.Path = "Authorization/UnsafeLogin?ver=1.0";
            request.QueryString.Add("loginName", loginName);
            request.QueryString.Add("password", password);
            request.Sign();
            var result = request.Kakao<OAuthLoginData>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            OAuthUser userData = GetUser(result.Data.UserToken);
            return userData;
        }
        /// <summary>
        /// 根据UserToken获取User信息
        /// </summary>
        /// <param name="token">UserToken</param>
        /// <returns>User信息</returns>
        public static OAuthUser GetUser(string token)
        {
            // http://oauth.test.tops001.com/User/GetUsersByTokens
            var request = new HttpRequest(oauthUrl);
            request.Path = "User/GetUser?ver=1.0";
            request.QueryString.Add("userToken", token);
            request.Sign();
            var result = request.Kakao<OAuthUser>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        /// <summary>
        /// 根据accesstoken获取User信息
        /// </summary>
        /// <param name="token">accesstoken</param>
        /// <returns>User信息</returns>
        public static OAuthUser GetUserByAk(string accesstoken)
        {
            // http://oauth.test.tops001.com/Authorization/GetUser
            var request = new HttpRequest(oauthUrl);
            request.Path = "Authorization/GetUser?ver=1.0";
            request.QueryString.Add("accessToken", accesstoken);
            request.Sign();
            var result = request.Kakao<OAuthUser>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }
        /// <summary>
        /// 根据AdminKid获取User信息
        /// </summary>
        /// <param name="adminKid">adminkid</param>
        /// <returns>user信息</returns>
        public static OAuthUser GetUserByAdminKid(int adminKid)
        {
            // http://oauth.test.tops001.com/User/GetUsersByTokens
            var request = new HttpRequest(oauthUrl);
            request.Path = "User/GetAdminToken?ver=1.0";
            request.QueryString.Add("adminkid", adminKid);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return GetUser(result.Data);
        }

        /// <summary>
        /// 根据AdminKid获取Token信息
        /// </summary>
        /// <param name="adminKid">adminkid</param>
        /// <returns>token</returns>
        public static string GetTokenByAdminKid(int adminKid)
        {
            // http://oauth.test.tops001.com/User/GetUsersByTokens
            var request = new HttpRequest(oauthUrl);
            request.Path = "User/GetAdminToken?ver=1.0";
            request.QueryString.Add("adminkid", adminKid);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        /// <summary>
        /// 根据BrokerKid获取User信息
        /// </summary>
        /// <param name="brokerKid">brokerkid</param>
        /// <returns>user信息</returns>
        public static OAuthUser GetUserByBrokerKid(int brokerKid)
        {
            // http://oauth.test.tops001.com/User/GetUsersByTokens
            var request = new HttpRequest(oauthUrl);
            request.Path = "User/GetBrokerToken?ver=1.0";
            request.QueryString.Add("brokerkid", brokerKid);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return GetUser(result.Data);
        }

        /// <summary>
        /// 根据BrokerKid获取Token信息
        /// </summary>
        /// <param name="brokerKid">brokerkid</param>
        /// <returns>token</returns>
        public static string GetTokenByBrokerKid(int brokerKid)
        {
            // http://oauth.test.tops001.com/User/GetUsersByTokens
            var request = new HttpRequest(oauthUrl);
            request.Path = "User/GetBrokerToken?ver=1.0";
            request.QueryString.Add("brokerkid", brokerKid);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        public static void BindAdminKID(string userToken, int adminKid)
        {
            //http://oauth.test.tops001.com/Bind/BindThirdPartyAccount
            var request = new HttpRequest(oauthUrl);
            request.Path = "Bind/BindThirdPartyAccount?ver=1.0";
            request.QueryString.Add("userToken", userToken);
            request.QueryString.Add("source", "admin");
            request.QueryString.Add("sourceid", adminKid);
            request.Sign();
            var result = request.Kakao<bool>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            if (!result.Data)
            {
                throw new Top.Web.WebApiException("绑定信息时出错");
            }
        }

        public static VerifyCode GetVerifyCode(string phone)
        {
            // http://notify.test.tops001.com/SendLogs/GetVerifyCode
            var request = new HttpRequest(notifyUrl);
            request.Path = "SendLogs/GetVerifyCode?ver=1.0";
            request.QueryString.Add("phone", phone);
            request.Sign();
            var result = request.Kakao<VerifyCode>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            return result.Data;
        }

        public static string GetVerifyCode_Full(string phone)
        {
            // http://notify.test.tops001.com/SendLogs/GetVerifyCode
            var request = new HttpRequest(notifyUrl);
            request.Path = "SendLogs/GetVerifyCode?ver=1.0";
            request.QueryString.Add("phone", phone);
            request.Sign();
            var result = request.Kakao<string>().Result;
            if (result.Code != 0)
            {
                throw new Top.Web.WebApiException(result.Message);
            }
            if (string.IsNullOrWhiteSpace(result.Data))
            {
                result.Data = "";
            }
            return result.Data;
        }

        public static void ErrorConvert(string code)
        {
            switch (code)
            {
                case "3004":
                    throw new Top.Web.WebApiException("您输入的是用户名不是正确的手机号码");
                default:
                    break;
            }
        }
    }

    public class VerifyCode
    {
        public string ContentParams { get; set; }

        public string SendTime { get; set; }
    }
}
